import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form, Icon as LegacyIcon } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Popover, Spin } from 'antd';
import moment from 'moment';
import 'moment/locale/zh-cn';
import { PrimaryC, PrimaryGhostC, FixedButtonC } from '../../../../comps';
import '../index.less';
import FormTableC from './components/formTableC';
import ImportFileC from './components/importFileC';
import GroupC from './components/groupC';
import ResultIndexC from './components/resultC';
import InitFormC from './components/InitFormC';
import { exportFile } from '@/src/utils/commonFunc';

@connect(({ portfolioOptimizationM, loading }) => ({
  portfolioOptimizationM,
  loading,
}))
@Form.create()
export default class BasicInfo extends PureComponent {
  state = {
    timeOutGap: 500,
    currentPage: 1, // news当前页码
    numInPage: 10, // 每页数量
    isShowExample: false, // 是否显示示例组合
    isShowWeight: false, // 是否显示配置权重
    initColumns: [
      {
        // 默认表头
        key: 'asset',
        title: '资产',
        isNeed: true,
      },
      {
        key: 'initWeight',
        title: '初始权重(%)',
        isNeed: true,
      },
      {
        key: 'expectReturn',
        title: '预期收益率(%)',
        isNeed: false,
      },
      {
        key: 'expectVolatility',
        title: '预期波动率(%)',
        isNeed: false,
      },
      {
        key: 'weightBottom',
        title: '权重下界(%)',
        isNeed: false,
      },
      {
        key: 'weightTop',
        title: '权重上界(%)',
        isNeed: false,
      },
      {
        key: 'group',
        title: '组别',
        isNeed: false,
      },
    ],
    weightMethodList: [
      // 配置权重
      { title: '等权重', value: '0', isSelect: false },
      { title: '归一化', value: '1', isSelect: false },
      { title: '清空', value: '2', isSelect: false },
    ],
    isSubmitOk: false, // 是否提交成功
    isShowResult: false, // 是否展示结果页
    visible: false, // 展示导入组合
    groupVisible: false, // 展示分组约束
    groupData: [], // 分组约束列表数据
    rangedate: [moment().subtract(1, 'years'), moment().subtract(1, 'days')],
    currentModel: 0, // 优化模型，
    isShowTrue: false, // 显示是否
  };

  componentDidMount() {
    // 查询示例组合列表
    this.props.dispatch({
      type: 'portfolioOptimizationM/getSamplePortList',
      payload: {},
      callback: (msg, data) => {
        if (msg == 'success') {
          this.setState({
            exampleList: [...data],
          });
        } else {
          this.setState({
            exampleList: [],
          });
        }
      },
    });
  }

  componentWillUnmount() {
    // 离开前清除models数据
    this.props.dispatch({
      type: 'portfolioOptimizationM/setState',
      payload: {
        resultDataObj: {
          config: {
            columns: [],
            dataSource: [],
          },
          performComp: {
            columns: [],
            dataSource: [],
          },
        }, // 结果页数据
      },
    });
    this.setState({
      isSubmitOk: false, // 是否提交成功
      isShowResult: false, // 是否展示结果页
    });
    // sessionStorage.removeItem('isShowTitle') //展示组合优化标题
  }

  // 切换列表是否下拉表格变化
  handleSelectChange = (e, type) => {
    const { initColumns } = this.state;
    initColumns.map((item) => {
      // 决定是否显示该列
      if (type == 'assetConst') {
        if (item.key == 'weightBottom') {
          item.isNeed = e == '0';
        }
        if (item.key == 'weightTop') {
          item.isNeed = e == '0';
        }
      } else if (item.key == type) {
        item.isNeed = e == '0';
        if (type == 'expectReturn') {
          // this.setState({
          //   isShowTrue:item.isNeed
          // })
          // this.props.form.setFieldsValue({
          //   expectVolatility:undefined
          // })
        }
      }
    });
    this.setState({
      initColumns: [...initColumns],
    });
  };

  // 优化模型切换
  selectCurrent = (e) => {
    this.setState({
      currentModel: e,
    });
  };

  // 相关设置 权重 示例 点击按钮 更新选中颜色
  handleClick = (val, type) => {
    const { weightMethodList, exampleList } = this.state;
    if (type == 'weight') {
      weightMethodList.map((item) => {
        if (item.value == val) {
          item.isSelect = true;
        } else {
          item.isSelect = false;
        }
      });
      this.setState({
        weightMethodList: [...weightMethodList],
      });
      this.child.setWeightBytype(val);
    } else {
      exampleList.map((item) => {
        if (item.value == val) {
          item.isSelect = true;
        } else {
          item.isSelect = false;
        }
      });
      this.setState({
        exampleList: [...exampleList],
      });
      // 获取示例组合对应的表格数据
      this.props.dispatch({
        type: 'portfolioOptimizationM/getSamplePortTable',
        payload: {
          id: val,
        },
        callback: (msg, data) => {
          if (msg == 'success') {
            const tableData = [];
            let sum = 0;
            data.map((item, index) => {
              tableData.push({
                order: index + 1,
                asset: {
                  value: item.asset,
                  label: item.title,
                  key: item.asset,
                },
                initWeight: item.initWeight,
              });
              sum += item.initWeight;
            });
            tableData.push({ order: '总计', initWeight: sum });
            this.child.setState({
              dataSource: tableData,
            });
          }
        },
      });
    }
  };

  // 提交 执行分析按钮
  submit = () => {
    const { dispatch, type } = this.props;
    const { initColumns, groupData } = this.state;
    const arr = this.child.submit();
    const values = this.initFormRef.submit();
    if (!arr) return; // 校验config表单数据，及表格数据
    const tempData = JSON.parse(JSON.stringify(arr.slice(0, arr.length - 1)));
    const configData = tempData.filter((item) => item.asset);
    configData.map((item) => {
      // 因为导入的原因  设置了labelInValue 所以提交之前做下处理
      const asset = item.asset.key;
      item.asset = asset;
      delete item.order;
      delete item.isRed;
    });
    const payload = {
      type,
      configData: {
        columns: initColumns.filter((item) => item.isNeed),
        dataSource: [...configData],
      },
      ...values,
      beginDate: values.beginDate.format('YYYY-MM-DD'),
      groupData: {
        dataSource: [...groupData],
        columns: [
          {
            // 默认表头
            key: 'group',
            title: '组名',
          },
          {
            key: 'weightBottom',
            title: '权重下界(%)',
          },
          {
            key: 'weightTop',
            title: '权重上界(%)',
          },
        ],
      },
    };
    if (type == '0') {
      if (!values.beginDate || !values.endDate) return;
      if (values.rollBacktest !== '0') delete values.freq; // 滚动回测为否 则频率不选
      payload.endDate = values.endDate.format('YYYY-MM-DD');
    }
    dispatch({
      type: 'portfolioOptimizationM/executeOptimization',
      payload,
      callback: (msg) => {
        if (msg == 'success') {
          // sessionStorage.setItem('isShowTitle', '1') //不展示组合优化标题
          this.props.dispatch({
            type: 'portfolioOptimizationM/setState',
            payload: {
              isShowTitle: false,
            },
          });
          this.setState({
            // 展示分析结果页面
            isSubmitOk: true,
            isShowResult: true,
          });
        }
      },
    });
  };

  // 重置reset
  reset = () => {
    this.initFormRef.reset(); // 重置表单
    const { exampleList } = this.state;
    this.result.setState({
      // 将结果页定位到第一个tab
      tab: '1',
    });
    exampleList.map((item) => (item.isSelect = false)); // 示例组合 配色重置
    this.setState({
      currentModel: 0, // 重置为默认值优化模型
      isShowExample: false, // 是否显示示例组合
      isShowWeight: false, // 是否显示配置权重
      initColumns: [
        {
          // 默认表头
          key: 'asset',
          title: '资产',
          isNeed: true,
        },
        {
          key: 'initWeight',
          title: '初始权重(%)',
          isNeed: true,
        },
        {
          key: 'expectReturn',
          title: '预期收益率(%)',
          isNeed: false,
        },
        {
          key: 'expectVolatility',
          title: '预期波动率(%)',
          isNeed: false,
        },
        {
          key: 'weightBottom',
          title: '权重下界(%)',
          isNeed: false,
        },
        {
          key: 'weightTop',
          title: '权重上界(%)',
          isNeed: false,
        },
        {
          key: 'group',
          title: '组别',
          isNeed: false,
        },
      ],
      weightMethodList: [
        // 配置权重
        { title: '等权重', value: '0', isSelect: false },
        { title: '归一化', value: '1', isSelect: false },
        { title: '清空', value: '2', isSelect: false },
      ],
      isSubmitOk: false, // 是否提交成功
      isShowResult: false,
      exampleList: [...exampleList],
      groupData: [],
    });
    // sessionStorage.removeItem('isShowTitle') //展示组合优化标题
    this.child.reset(); // 清空表格数据
    this.childGroup.reset(); // 清空分组约束数据
    this.props.dispatch({
      type: 'portfolioOptimizationM/setState',
      payload: {
        resultDataObj: {
          config: {
            columns: [],
            dataSource: [],
          },
          performComp: {
            columns: [],
            dataSource: [],
          },
        }, // 结果页数据
      },
    });
  };

  // getImportData 获取导入的数据，替换页面上的数据
  getImportData = (data) => {
    // 设置不同优化模型 显示不同的条件
    this.setState(
      {
        currentModel: data.optimizeObject,
      },
      () => {
        this.initFormRef.importData(data);
      },
    );
    this.handleSelectChange(`${data.assetConst}`, 'assetConst');
    this.handleSelectChange(`${data.groupConst}`, 'group');
    if (data.optimizeObject == 0) {
      this.handleSelectChange(`${data.expectVolatility}`, 'expectVolatility');
      this.handleSelectChange(`${data.expectReturn}`, 'expectReturn');
    } else {
      this.handleSelectChange('1', 'expectVolatility');
      this.handleSelectChange('1', 'expectReturn');
    }
    if (data.groupConfigData) {
      const groupData = data.groupConfigData.dataSource.map((item, index) => {
        item.order = index + 1;
        item.id = item.group;
        return item;
      });
      this.childGroup.setState({
        dataSource: [...groupData],
      });
      this.setState({
        // 表格的组别下拉列表
        groupData: [...groupData],
      });
    }
    const configData = [];
    let sum = 0;
    data.assetConfigData &&
      data.assetConfigData.dataSource.map((item, index) => {
        item.order = index + 1;
        const { title } = item;
        const { asset } = item;
        delete item.title;
        item.asset = {
          key: asset,
          value: asset,
          label: title,
        };
        configData.push(item);
        sum += item.initWeight;
      });
    configData.push({ order: '总计', initWeight: sum });
    this.child.setState({
      dataSource: [...configData],
    });
  };

  // 获取分组约束 对应的组别列表
  getGroupData = (arr) => {
    const groupData = JSON.parse(JSON.stringify(arr));
    this.setState(
      {
        groupData: [...groupData],
      },
      () => {
        const arr = this.child.state.dataSource;
        arr.map((item, index) => {
          // 查找已选择的组别 是否已被删除，删除则置空
          if (index == arr.length - 1) return;

          if (!item.group) return;
          const idList = this.state.groupData.map((group) => {
            return group.id;
          });
          if (!idList.filter((id) => id == item.group).length) {
            delete item.group;
          }
        });
        this.child.setState({
          dataSource: [...arr],
        });
      },
    );
  };

  // 分组约束、相关设置
  setBtnRender = () => {
    const { isShowExample, isShowWeight, weightMethodList, exampleList = [] } = this.state;
    // 相关设置的hover 悬浮框
    const content = (
      <div>
        <div className='relativeSet'>
          <p
            onClick={() => {
              if (!exampleList.length) return;
              this.setState({ isShowExample: !isShowExample });
            }}
          >
            <LegacyIcon type={isShowExample == false ? 'caret-right' : 'caret-down'} style={{ cursor: exampleList.length ? 'inherit' : 'not-allowed' }} />
            示例组合
          </p>
          <ul style={{ display: isShowExample == true ? 'block' : 'none' }}>
            {exampleList &&
              exampleList.map((item, key) => {
                return (
                  <li
                    key={key}
                    value={item.value}
                    className={item.isSelect == true ? 'selectColor' : ''}
                    onClick={() => {
                      this.handleClick(item.value, 'example');
                    }}
                  >
                    {item.title}
                  </li>
                );
              })}
          </ul>
        </div>
        <div className='relativeSet'>
          <p
            onClick={() => {
              this.setState({ isShowWeight: !isShowWeight });
            }}
          >
            <LegacyIcon type={isShowWeight == false ? 'caret-right' : 'caret-down'} />
            配置权重
          </p>
          <ul style={{ display: isShowWeight == true ? 'block' : 'none' }}>
            {weightMethodList.map((item, key) => {
              return (
                <li
                  key={key}
                  value={item.value}
                  className={item.isSelect == true ? 'selectColor' : ''}
                  onClick={() => {
                    this.handleClick(item.value, 'weight');
                  }}
                >
                  {item.title}
                </li>
              );
            })}
          </ul>
        </div>
      </div>
    );
    return (
      <div className='setBtn'>
        <PrimaryGhostC
          title='分组约束'
          onClick={() => {
            this.setState({ groupVisible: true });
          }}
        />
        <Popover placement='bottomRight' trigger='click' content={content}>
          <div>
            <PrimaryGhostC title='相关设置' />
          </div>
        </Popover>
      </div>
    );
  };

  export = (e) => {
    // 模板下载
    if (this.props.type == '0') {
      exportFile('api/v1/bondTrade/download-template', { fileName: 'portOptimizationTemplate_stock.xlsx' });
    } else if (this.props.type == '1') {
      exportFile('api/v1/bondTrade/download-template', { fileName: 'portOptimizationTemplate_bond.xlsx' });
    }
  };

  render() {
    const {
      portfolioOptimizationM: { resultDataObj },
      loading,
    } = this.props;
    const { groupData, isSubmitOk, isShowResult, initColumns, currentModel } = this.state;
    return (
      <div>
        <Spin spinning={loading.effects['portfolioOptimizationM/executeOptimization'] == true}>
          <FixedButtonC
            topHtml={
              <>
                <div className='config' style={{ display: !isShowResult ? 'block' : 'none' }}>
                  <div style={{ marginBottom: '11px' }}>
                    <ImportFileC getImportData={this.getImportData} />
                    <a
                      onClick={() => {
                        this.export();
                      }}
                      style={{ verticalAlign: 'bottom', marginLeft: '10px' }}
                    >
                      {this.props.type == '0' ? '股票模板' : this.props.type == '1' ? '债券模板' : ''}
                    </a>
                  </div>
                  <InitFormC
                    onRef={(ref) => {
                      this.initFormRef = ref;
                    }}
                    type={this.props.type}
                    currentModel={currentModel}
                    selectCurrent={this.selectCurrent}
                    handleSelectChange={this.handleSelectChange}
                  />
                  {this.setBtnRender()}
                  <FormTableC
                    type={this.props.type}
                    initColumns={initColumns}
                    currentModel={this.state.currentModel}
                    groupData={groupData}
                    onRef={(ref) => {
                      this.child = ref;
                    }}
                  />
                  <GroupC
                    onRef={(ref) => {
                      this.childGroup = ref;
                    }}
                    visible={this.state.groupVisible}
                    triggleVisible={(e) => {
                      this.setState({ groupVisible: e });
                    }}
                    getGroupData={this.getGroupData}
                    oldData={this.state.groupData}
                  />
                </div>
                <div style={{ display: isShowResult ? 'block' : 'none' }}>
                  <ResultIndexC
                    totalData={resultDataObj}
                    onRef={(ref) => {
                      this.result = ref;
                    }}
                  />
                </div>
              </>
            }
            bottomHtml={
              <div style={{ width: '100%', textAlign: 'center' }}>
                <div className='footerBtn'>
                  {!isShowResult && (
                    <>
                      <span
                        className={isSubmitOk ? 'mainColor' : 'disableColor'}
                        onClick={() => {
                          if (isSubmitOk) {
                            this.setState({ isShowResult: true });
                            this.props.dispatch({
                              type: 'portfolioOptimizationM/setState',
                              payload: {
                                isShowTitle: false,
                              },
                            });
                          }
                        }}
                      >
                        查看分析结果
                      </span>
                      <PrimaryC
                        title='提交'
                        onClick={() => {
                          this.submit();
                        }}
                      />
                      <PrimaryGhostC
                        title='重置'
                        onClick={() => {
                          this.reset();
                        }}
                      />
                    </>
                  )}
                  {isShowResult && (
                    <PrimaryC
                      title='返回'
                      onClick={() => {
                        this.setState({ isShowResult: false });
                        this.props.dispatch({
                          type: 'portfolioOptimizationM/setState',
                          payload: {
                            isShowTitle: true,
                          },
                        });
                      }}
                    />
                  )}
                </div>
              </div>
            }
          />
        </Spin>
      </div>
    );
  }
}
